<script setup lang="ts" name="AddDrugStorehouse">
import dDialog from '@/components/dDialog/dDialog.vue'
import dFrom from '@/components/dFrom/dFrom.vue'
import {FromItem} from '@/components/dFrom/dFrom'
import {onMounted, PropType, reactive, ref, watch} from 'vue'
import {ElMessage, FormRules} from 'element-plus'
import {Letter, NoChinese, NotLeadingAndTrailingSpaces, transfDicArrData} from '@/util/common'
import {DrugStoreList, getUpperCase, saveDrugStore} from '@/api/medicalExaminerDesk/beginPhysicalExamination/mainMedication'
import userCommon from '@/store/common'
import {SeleteData} from '@/api/config'
const common = userCommon.setup().store
const props = defineProps({
  //显示
  showDialog: {
    type: Boolean,
    required: true
  },
  dialogType: {
    type: String,
    required: true
  },
  // 药品数据
  drugData: {
    type: Object as PropType<DrugStoreList | undefined>,
    required: true
  }
})

const emits = defineEmits(['close'])

//表单清除控制
const resetFieldsFlag = ref(false)
const validateFlag = ref(false)

// 是否保存并且继续
const continueFlag = ref(false)

// 是否转换拼音码
const convertPinyin = ref<boolean>(!props.drugData?.pinyinCode)

// 保存加载
const showSaveLoading = ref<boolean>(false)

// 用法
const drugUseMethodOptions = ref<Array<SeleteData>>([])
// 用药频率
const frequencyOptions = ref<Array<SeleteData>>([])

// 剂量单位
const doseUnitOptions = ref<Array<SeleteData>>([])

// 时间单位
const drugTimeUnitOptions = ref<Array<SeleteData>>([])

// 服药依从性
const drugCompliableOptions = ref<Array<SeleteData>>([])

// 空数据
const emptyData: DrugStoreList = {}

// 新增药品
const fromData = reactive<DrugStoreList>({...props.drugData})

//表单项
const fromItems = ref<Array<FromItem>>([
  {
    label: '药品代码',
    prop: 'drugCode',
    placeholder: '请输入药品代码',
    type: 'input'
  },
  {
    label: '药品名称',
    prop: 'drugName',
    placeholder: '请输入药品名称',
    type: 'slot',
    slotName: 'drugName'
  },
  {
    label: '拼音码',
    prop: 'pinyinCode',
    placeholder: '请输入拼音码',
    type: 'input'
  },
  {
    label: '用法',
    prop: 'drugUseMethod',
    placeholder: '请选择用法',
    type: 'selete',
    seleteData: drugUseMethodOptions.value
  },
  {
    label: '用量',
    prop: 'frequency',
    placeholder: '请选择用药频率',
    type: 'selete',
    seleteData: frequencyOptions.value
  },
  {
    label: '用药时间',
    prop: 'drugUseTime',
    type: 'slot',
    slotName: 'drugUseTime'
  },
  {
    label: '',
    prop: 'dose',
    type: 'slot',
    slotName: 'dose'
  },
  {
    label: '服药依从性',
    prop: 'drugCompliable',
    placeholder: '请选择服药依从性',
    type: 'selete',
    seleteData: drugCompliableOptions.value
  }
])

const rules = reactive<FormRules>({
  drugCode: [
    {required: true, message: '请输入药品代码', trigger: ['change', 'blur']},
    {
      message: '最多50位字母、数字、字符',
      trigger: ['change', 'blur'],
      max: 50
    },
    {
      message: '请输入字母、数字、字符',
      pattern: NoChinese,
      trigger: ['change', 'blur']
    },
    {
      message: '首尾不能为空格',
      pattern: NotLeadingAndTrailingSpaces,
      trigger: ['change', 'blur']
    }
  ],
  drugName: [
    {
      required: true,
      message: '请输入药品名称',
      trigger: ['change', 'blur']
    },
    {
      message: '最多50个字符',
      trigger: ['change', 'blur'],
      max: 50
    },
    {
      message: '首尾不能为空格',
      pattern: NotLeadingAndTrailingSpaces,
      trigger: ['change', 'blur']
    }
  ],
  pinyinCode: [
    {
      message: '最多50个字符',
      trigger: ['change', 'blur'],
      max: 50
    },
    {
      message: '请输入字母',
      pattern: Letter,
      trigger: ['change', 'blur']
    }
  ],
  dose: [
    {
      message: '最多20个字符',
      trigger: ['change', 'blur'],
      max: 20
    },
    {
      message: '首尾不能为空格',
      pattern: NotLeadingAndTrailingSpaces,
      trigger: ['change', 'blur']
    }
  ]
})

/**
 * @description: 关闭弹窗
 * @return {*}
 */
const onCancel = () => {
  emits('close')
}
/**
 * @description: 关闭弹窗
 * @return {*}
 */
const onClose = () => {
  emits('close')
}

/**
 * @description: 保存
 * @return {*}
 */
const onConfirm = () => {
  validateFlag.value = !validateFlag.value
  continueFlag.value = false // 保存不继续
}

/**
 * @description: 保存并继续
 * @return {*}
 */
const onContinueConfirm = () => {
  validateFlag.value = !validateFlag.value
  continueFlag.value = true // 保存并且继续
}

/**
 * @description: 根据中文获取拼音首字母大写
 * @return {*}
 */
const onUpperCaseChange = (e) => {
  // 没有拼音码才触发自动转换
  if (convertPinyin.value) {
    const chinese = e.replace(/[^\u4e00-\u9fa5]/gi, '')
    e &&
      getUpperCase({drugName: chinese}).then((res) => {
        fromData.pinyinCode = res.data?.data || ''
      })
  }
}

watch(
  () => fromData.pinyinCode,
  () => {
    // 清空拼音码要继续触发转换
    !fromData.pinyinCode && (convertPinyin.value = true)
  }
)

//表单验证通过事件
const onSubmit = () => {
  showSaveLoading.value = true
  const params = {
    id: fromData.id,
    drugName: fromData.drugName, // 药品名称
    drugCode: fromData.drugCode, // 药品代码
    pinyinCode: fromData.pinyinCode || null, // 拼音码
    drugUseMethod: fromData.drugUseMethod || null, // 用法 - 字典
    frequency: fromData.frequency || null, // 用药频率 - 字典
    dose: fromData.dose || null, // 用药剂量
    doseUnit: fromData.doseUnit, // 用药剂量单位 - 字典
    drugTimeUnit: fromData.drugTimeUnit, //用药时间单位 - 字典
    drugUseTime: fromData.drugUseTime, // 用药时间
    drugCompliable: fromData.drugCompliable || null // 服药依从性 - 字典
  }
  saveDrugStore(params)
    .then(() => {
      ElMessage.success('保存成功！')
      resetFieldsFlag.value = !resetFieldsFlag.value
      continueFlag.value ? Object.assign(fromData, emptyData) : emits('close')
    })
    .finally(() => {
      showSaveLoading.value = false
    })
}

/**
 * @description: 获取下拉字典
 * @return {*}
 */
const getDict = () => {
  drugUseMethodOptions.value.length = 0 // 用法
  frequencyOptions.value.length = 0 // 用药频率
  doseUnitOptions.value.length = 0 // 剂量单位
  drugTimeUnitOptions.value.length = 0 // 时间单位
  drugCompliableOptions.value.length = 0 // 服药依从性
  // 用法字典
  common.getDicData('drug_use_method').then((res) => {
    const arr: Array<SeleteData> = transfDicArrData(res)
    arr.forEach((item) => {
      drugUseMethodOptions.value.push(item)
    })
  })
  // 用药频率字典
  common.getDicData('frequency').then((res) => {
    const arr: Array<SeleteData> = transfDicArrData(res)
    arr.forEach((item) => {
      frequencyOptions.value.push(item)
    })
  })
  // 用药剂量单位字典
  common.getDicData('dose_unit').then((res) => {
    const arr: Array<SeleteData> = transfDicArrData(res)
    arr.forEach((item) => {
      doseUnitOptions.value.push(item)
    })
  })
  // 用药时间单位字典
  common.getDicData('drug_time_unit').then((res) => {
    const arr: Array<SeleteData> = transfDicArrData(res)
    arr.forEach((item) => {
      drugTimeUnitOptions.value.push(item)
    })
  })
  // 服药依从性字典
  common.getDicData('drug_compliable').then((res) => {
    const arr: Array<SeleteData> = transfDicArrData(res)
    arr.forEach((item) => {
      drugCompliableOptions.value.push(item)
    })
  })
}

onMounted(() => {
  getDict()
})
</script>
<template>
  <d-dialog
    :title="dialogType === 'edit' ? '编辑药品' : '新增药品'"
    :show-dialog="showDialog"
    :show-save-loading="showSaveLoading"
    :width="868"
    @cancel="onCancel"
    @close="onClose"
    @confirm="onConfirm"
  >
    <d-from
      label-position="right"
      :label-width="100"
      :reset-fields-flag="resetFieldsFlag"
      :validate-flag="validateFlag"
      :form-data="fromData"
      :rules="rules"
      :form-items="fromItems"
      :form-line-num="2"
      @submit="onSubmit"
    >
      <template #drugName>
        <el-input v-model="fromData.drugName" placeholder="请输入药品名称" clearable @blur="onUpperCaseChange(fromData.drugName)" />
      </template>
      <template #drugUseTime>
        <el-input-number v-model="fromData.drugUseTime" placeholder="请输入用药时间" :controls="false" :max="9999" clearable class="width-1evel-2 margin-level-1" />
        <el-select v-model="fromData.drugTimeUnit" placeholder="请选择时间单位" clearable class="width-1evel-3">
          <el-option v-for="item in drugTimeUnitOptions" :key="item.value + ''" :label="item.label" :value="item.value" />
        </el-select>
      </template>
      <template #dose>
        <el-input v-model="fromData.dose" placeholder="请输入用药剂量" clearable class="width-1evel-2 margin-level-1" />
        <el-select v-model="fromData.doseUnit" placeholder="请选择剂量单位" clearable class="width-1evel-3">
          <el-option v-for="item in doseUnitOptions" :key="item.value + ''" :label="item.label" :value="item.value" />
        </el-select>
      </template>
    </d-from>
    <template v-if="dialogType === 'add'" #append>
      <el-button type="primary" :loading="showSaveLoading" @click="onContinueConfirm">
        保存并继续
      </el-button>
    </template>
  </d-dialog>
</template>
<style scoped lang="less">
.width-1evel-2 {
  width: calc(100% - 49% - 8px);
}
.width-1evel-3 {
  width: 49%;
}
.margin-level-1 {
  margin-right: 8px;
}
</style>
